package com.black.knight.chess.calls;

import org.restlet.data.ChallengeScheme;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

import android.view.MenuInflater;

import com.black.knight.chess.R;
import com.black.knight.chess.SahMatActivity;
import com.black.knight.chess.common.ActivityEnum;
import com.black.knight.chess.common.User;
import com.black.knight.chess.common.UsersResource;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.model.SettingsModel;
import com.black.knight.chess.utils.Utils;

public class AutoLoginUserCall implements Runnable {

	private User user;
	
	private SahMatActivity context;
	
	private User base = null;
	
	public AutoLoginUserCall(User user, SahMatActivity context) {
		this.context = context;
		this.user = user;
	}
	
	@Override
	public void run() {
		final ClientResource cr = new ClientResource(SettingsModel.SERVICE_URL + "/users");
		
		cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, user.getUsername(), user.getPassword());
		cr.setRequestEntityBuffering(true);
		
		UsersResource resource = cr.wrap(UsersResource.class);
		
		try {
			base = resource.login((user));
		} catch (final Exception e) {
			if(e instanceof ResourceException && ((ResourceException) e).getStatus().getCode() == 401) {
				base = new User(false, context.getResources().getString(R.string.incorrect_username_or_password)); 
			} else {
				base = new User(false, context.getResources().getString(R.string.unable_to_connect_to_server));
			}
		}
		
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {					
					if(base.getSuccess()) {
						SettingsModel.getInstance().setLoggedUser(base);
						
				    	Utils.displayToastMessage(context, context.getResources().getString(R.string.user_logged_in_successfully));
				    	
			        	MenuInflater inflater = SahModel.context.getMenuInflater();
			        	
			        	if(SahModel.context.menu != null) {
				        	SahModel.context.menu.clear();
				        	if(SettingsModel.getInstance().getLoggedUser() != null) {
				            	inflater.inflate(R.menu.chess_menu_signout, SahModel.context.menu);
				            } else {
				            	inflater.inflate(R.menu.chess_menu, SahModel.context.menu);
				            }
			        	}
			        	
			        	PublishActivityCall call = new PublishActivityCall(ActivityEnum.AUTO_SIGN_IN, base.getUsername(), base.getName(), "");			    		
			    		SettingsModel.EXECUTOR_SERVICE.execute(call);
					}
				} catch (Exception e) { }
			}
		});
	}
}
